#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'dong'

import re
import requests
from bs4 import BeautifulSoup


class se(object):

    def __init__(self):
        self.s = requests.session()
        self.headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language":"zh-CN,zh;q=0.8",
            "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36",
            "Host": "www.78gk.com",
            "Referer": "http://www.78gk.com/fabu.php?catid=61&cityid=0",
            # "Content-Type": "multipart/form-data; charset=UTF-8"
            # "Content-Type": "text/html; charset=gbk"
        }

    def get_city(self):
        '''

        :return:
        '''

        province_dict = {
            '安徽': 8,
            '北京': 1,
            '重庆': 4,
            '福建': 10,
            '广东': 9,
            '广西': 11,
            '贵州': 22,
            '甘肃': 29,
            '海南': 12,
            '河南': 13,
            '湖北': 14,
            '湖南': 15,
            '黑龙江': 18,
            '河北': 24,
            '江苏': 6,
            '江西': 16,
            '吉林': 19,
            '辽宁': 17,
            '内蒙古': 26,
            '宁夏': 30,
            '青海': 31,
            '上海': 3,
            '山东': 5,
            '四川': 20,
            '山西': 25,
            '陕西': 27,
            '天津': 2,
            '西藏': 23,
            '新疆': 28,
            '云南': 21,
            '浙江': 7,
        }

        # 获取省份
        # with open('p.html', 'r') as fd:
        #     c = fd.read()
            # patt = re.compile(r'<option.+?>(.+?)</option>')
            # patt = re.compile(r'<option value=\"(.+?)\">(.+?)</option>')
            # option = patt.findall(c)
            # print option[1:]
            # for i in option[1:]:
            #     print "'"+i[1].split('.')[1].decode('utf-8')+"': "+str(i[0])+','

            # print type(option[1].decode('utf-8').encode('gbk'))
            # print option[2].decode('utf-8')

        with open('city_78.py', 'a') as fd:

            for v in province_dict.values():
                # print v
                # 获取城市
                print v
                # url = 'http://www.360guakao.com/include/selectwhere.php?action=getarea&parentid={0}&currentid=&delstreet=1'.format(v)
                url = 'http://www.78gk.com/include/selectwhere.php?action=getarea&parentid={0}&currentid=&delstreet=1'.format(v)
                r =requests.get(url, headers=self.headers)
                # print r.content
                # patt = re.compile(r'<option.+?>(.+?)</option>')
                patt = re.compile(r'<option value=\\\'(.+?)>(.+?)</option>')
                option = patt.findall(r.content)
                # print option
                fd.write('def city_{0}(self, value):\n'.format(v))
                fd.write('    data = {\n')
                for o in option[1:]:
                    # print type(o[1])
                    # print o[1]
                    # print o[1].encode('gbk'), o[0].strip().replace("\\'", '')

                    d = "        '"+o[1]+"': "+o[0].strip().replace("\\'", '')+","
                    # print str(d.encode('gbk'))
                    fd.write(d+'\n')
                fd.write('    }\n')
                fd.write('    return data.get(value)')
                fd.write('\n\n')


    def post_msg(self):
        '''

        :return:
        '''
        print 'post...'
        login_url = 'http://www.78gk.com/login.php'
        login_data = {
            'action': 'dopost',
            'log_submit': '������¼',
            'memory': 'on',
            'mod': 'login',
            'url': '',
            'userid': '17727766372',
            'userpwd': 'ab654321',
        }
        login = self.s.post(url=login_url, data=login_data)
        print login.status_code
        print login.headers
        print login.content
        _cookies = login.cookies

        post_url = 'http://www.78gk.com/fabu.php?action=input'

        post_data = {
            "act": (None, 'dopost'),
            "areaid": (None, '106'),
            "catid": (None, '61'),
            # "catid": (None, '61'),
            "cityid": (None, '6'),
            "contact_who": (None, '�'),
            "content": (None, u'江苏无锡勘测院，急招注册岩土（退休也可）若干名，初转不限，3年一次付，退休也可，只挂证，不挂章'.encode('gbk')),
            "endtime": (None, '0'),
            "extra[jiage]": (None, '1'),
            "extra[leixing]": (None, '1'),
            "extra[zhicheng]": (None, '1'),
            "extra[zhuce]": (None, '1'),
            "id": (None, ''),
            "ismember": (None, '1'),
            "lat": (None, ''),
            "lng": (None, ''),
            "mappoint": (None, '1'),
            "mixcode": (None, '5d1c53d4228ab35a0f7b18cb656967a9'),
            "qq": (None, '332899008'),
            "tel": (None, '17727766372'),
            "title": (None, '急招注册岩土（退休也可）若干名'.decode('utf-8').encode('gbk')),
        }

        p = self.s.post(url=post_url, files=post_data, cookies=_cookies, headers=self.headers)
        print p.status_code
        print p.headers
        with open('a.html', 'w') as f:
            f.write(p.content)

        print p.content


if __name__ == '__main__':
    s = se()
    # s.post_msg()
    s.get_city()